#!/usr/bin/env python
#-*-coding:utf-8-*-

# windows_oss.py is part of "lemon-py" (http://code.google.com/p/lemon-py/).
# Copyright (C) 2010  - JBC <JBC dot Develop at gmail dot com >

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


################################################################################
# DOCS
################################################################################

"""Single innstance class and utilities for windows os"""


################################################################################
# META
################################################################################

__version__ = "0.1"
__license__ = "GPL3"
__author__ = "JBC"
__since__ = "0.1"
__date__ = "2010-06-23"

################################################################################
# IMPORTS
################################################################################

import hashlib

from win32event import CreateMutex
from win32api import CloseHandle, GetLastError
from winerror import ERROR_ALREADY_EXISTS

import core


################################################################################
# CLASS
################################################################################

class SingleInstance(core.SingleInstanceBase):

    def setup(self, **kwargs):
        """ Setup the app for only one instance run
        
        @param mutex: the name of the app

        """
        name = kwargs["mutex"]
        key = hashlib.sha1(name).hexdigest()
        mutexname = "%s_{%s}" % (name, key)
        self.mutex = CreateMutex(None, False, mutexname)
        self.lasterror = GetLastError()

    def isrunning(self):
        return (self.lasterror == ERROR_ALREADY_EXISTS)

    def __del__(self):
        if getattr(self, "mutex", None):
            CloseHandle(self.mutex)

            
################################################################################
# MAIN
################################################################################

if __name__ == "__main__":
    print __doc__

